package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.RoleDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Role;
import com.itheima.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        Page<Role> page = roleDao.findPage(queryString);
        List<Role> result = page.getResult();
        long total = page.getTotal();
        return new PageResult(total,result);
    }

    @Override
    public void add(Role role, Integer[] permissionIds) {
        roleDao.add(role);
        Integer roleId = role.getId();
        System.out.println(roleId);
        this.setRoleAndPermission(roleId,permissionIds);
    }

    //删除
    @Override
    public void del(Integer id) {
        roleDao.delRoleAndPermission(id);
        roleDao.delRole(id);
    }

    //根据Id查询角色
    @Override
    public Role findById(Integer id) {
        Role role = roleDao.findById(id);
        return role;
    }

    @Override
    public List<Integer> findPermissionIdsByRoleId(Integer id) {
        List<Integer> permissionIds = roleDao.findPermissionIdsByRoleId(id);
        return permissionIds;
    }

    @Override
    public void edit(Role role, Integer[] permissionIds) {
        //修改角色基本信息，操作角色t_role表
        roleDao.edit(role);
        //清理当前角色关联的权限，操作中间关系表t_role_permission表
        roleDao.deleteAssocication(role.getId());
        //重新建立当前角色和权限的关联关系
        Integer roleId = role.getId();
        this.setRoleAndPermission(roleId,permissionIds);
    }



    //建立角色和权限多对多关系
    public void setRoleAndPermission(Integer roleId,Integer[] permissionIds){
        if(permissionIds != null && permissionIds.length > 0){
            for (Integer permissionId : permissionIds) {
                Map<String,Integer> map = new HashMap<>();
                map.put("role_id",roleId);
                map.put("permission_id",permissionId);
                roleDao.setRoleAndPermission(map);
            }
        }
    }

    @Override
    public List<Role> findAll() {
        return roleDao.findAll();
    }
}
